<?php

namespace core\event;

use app\bll\MsgChannel;
use app\bll\MsgTemplate;
use ReflectionClass;

class Message
{
    public function dispatch(array $eventdata)
    {
        $event = $eventdata['ident'];
        $data  = $eventdata['data'];

        //根据钩子获取信息模板
        $msgTemplate = new MsgTemplate();
        $templates   = $msgTemplate->selectByHookIdent($event);
        //获取通道

        $bllMsgChannel = new MsgChannel();
        $channels      = $bllMsgChannel->select();
        $channels      = array_column($channels, null, 'id');

        foreach ($templates as $temp) {

            //获取模板中的所有变量
            $pattern = '/{#(.*?)#}/';
            $matches = [];
            $temmplatevariable = [];
            $mathresult = preg_match_all($pattern, $temp['content'], $matches);
            if ($mathresult !== false) {
                $temmplatevariable = isset($matches[1]) ? $matches[1] : [];
            }



            $channel = $temp['channel'];
            if (!$channel) {
                continue;
            }

            $channelids = explode(',', trim($channel, ','));

            foreach ($channelids as $chid) {
                //获取通道信息调用的扩展
                list($extendident, $class, $method) = explode('/', $channels[$chid]['extend']);

                $extendclass = '\\component\\extend\\' . $extendident . '\\' . $class;
                if (!class_exists($extendclass)) {
                    continue;
                }
                $reflectionClass = new ReflectionClass(
                    $extendclass
                );

                $method = $reflectionClass->getMethod($method);
                if ($method->isPublic()) {
                    $instance = $reflectionClass->newInstance();
                    $content = $temp['content'];
                    foreach ($data as $dkey => $d) {
                        if (!is_string($d)) {
                            continue;
                        }
                        $content =  str_replace('{#' . $dkey . '#}', $d, $content);
                    }

                    $method->invoke($instance, [
                        'variable' => $temmplatevariable,   //模板中所有的变量
                        'data'              => $data,       //传递数据
                        'message'           => [            //消息
                            'msgid'       => $temp['msgid'],     //模板ID
                            'title'       => $temp['title'],     //标题
                            'content'     => $content,           //内容 替换标签后的
                            'tempcontent' => $temp['content'],   //内容 未替换的
                        ]
                    ]);
                }
            }
        }
    }
}
